/* eslint-disable no-use-before-define */
/**
 * 简历推荐/不推荐
 * 大拇哥赞和踩组合
 * @param {} props
 */

import React, { useMemo } from 'react';
import { Divider, Row, message } from 'antd';
import { ThumbComment } from '@/molecules';
import AuthComponent from '@/utils/auth/AuthComponent';
import { setResumeDislike, setResumeLike } from '../service';
import { CommentModal } from '../components';

// 评价结果类型 0：未评价 1：赞 2： 踩
const mapping = {};
mapping[(mapping.like = 1)] = 'like';
mapping[(mapping.dislike = 2)] = 'dislike';

const useCommentProps = (commentType, value, immutable, comment, flag, curFlag) => {
    const ret = useMemo(() => {
        const r = { type: commentType, comment };
        // if (!immutable && value) {
        //     if (mapping[value] === commentType) {
        //         r.visited = true;
        //     } else {
        //         r.disabled = true;
        //     }
        // }
        if (curFlag === 1) {
            r.visited = true;
        }
        return r;
    }, [commentType, value, immutable, comment, flag]);
    return ret;
};
const reducerTypes = {
    close: 'CLOSE',
    like: 'SHOW_LIKE',
    dislike: 'SHOW_DISLIKE'
};

// 弹框中的属性
const modalReducer = (state, type) => {
    if (type === reducerTypes.close) {
        return { ...state, visible: false };
    }
    if (type === reducerTypes.like) {
        return { ...state, title: '推荐简历', commentLabel: '推荐理由', visible: true };
    }
    if (type === reducerTypes.dislike) {
        return {
            ...state,
            title: '不推荐简历',
            commentLabel: '不推荐理由',
            visible: true
        };
    }
    return state;
};

// function transferUsernamesToComment(names, suffix) {
//     if (!names || !names.length) {
//         return '';
//     }
//     return `${names.join('、')} ${suffix}`;
// }
const ThumbCommentGroup = props => {
    const { initState = {}, immutable, onChange, resumeId, record = {}, onRefresh } = props;
    // 组件相关状态
    const [state, setState] = React.useState({});
    const changeState = ({ evaluateType } = {}) => {
        // const likeComment = {
        //     desc: transferUsernamesToComment(praiseEmployeeNameList, '推荐'),
        //     count: praiseEmployeeNameList.length
        // };
        // const dislikeComment = {
        //     desc: transferUsernamesToComment(trampleEmployeeNameList, '不推荐'),
        //     count: trampleEmployeeNameList.length
        // };
        const likeComment = {
            desc: record?.praiseEmployeeVOList || [],
            count: record?.praiseEmployeeVOList?.length || 0
        };
        const dislikeComment = {
            desc: record?.trampleEmployeeVOList || [],
            count: record?.trampleEmployeeVOList?.length || 0
        };
        setState(val => ({ ...val, likeComment, dislikeComment, evaluateType }));
    };
    // 操作类型，赞/踩，like赞，dislike踩
    const [operate, setOperate] = React.useState();
    React.useEffect(() => {
        changeState(initState);
    }, [record]);
    const likeProps = useCommentProps(
        'like',
        state.evaluateType,
        immutable,
        state.likeComment,
        record?.trampleFlag || 0,
        record?.praiseFlag || 0
    );
    const dislikeProps = useCommentProps(
        'dislike',
        state.evaluateType,
        immutable,
        state.dislikeComment,
        record?.praiseFlag || 0,
        record?.trampleFlag || 0
    );
    const [modalProps, modalDispatch] = React.useReducer(modalReducer, {
        visible: false
    });
    // 弹框ok
    const handleOkClick = async comment => {
        const fn = operate === 'like' ? setResumeLike : setResumeDislike;
        const msg = operate === 'like' ? '推荐' : '不推荐';
        const { code, data = {} } = await fn(resumeId, comment);
        if (code !== 10000) {
            message.error(`${msg}简历失败！`);
            return;
        }
        modalDispatch(reducerTypes.close); // 关闭弹窗
        if (operate === 'like') {
            message.success('推荐成功');
        } else {
            message.success(`已${msg}简历`);
        }
        const ret = { ...data, evaluateType: mapping[operate] };
        // 更新组件状态
        changeState(ret);
        if (onChange) {
            onChange(resumeId, ret);
        }
        if (onRefresh) {
            onRefresh();
        }
    };
    // 弹框cancel
    const handleCancelClick = () => {
        modalDispatch(reducerTypes.close); // 关闭弹窗
    };

    // 赞/踩点击
    const handleClick = type => {
        // if (type === 'like' && record.trampleFlag) {
        //     return;
        // }
        // if (type === 'dislike' && record.praiseFlag) {
        //     return;
        // }
        // 记录当前动作
        setOperate(type);
        // 弹框
        modalDispatch(reducerTypes[type]);
    };

    const flag = {
        status: operate === 'like' ? record?.praiseFlag || 0 : record?.trampleFlag || 0, // 判断是否已经点赞、踩过。点赞或踩过，status = 1。
        // CommentModal 中， Alert 显示的信息
        type:
            operate === 'like'
                ? `您已对${record?.talentName || ''}的简历做过推荐，本次可能是重复操作`
                : `您已对${record?.talentName || ''}的简历做过不推荐，本次可能是重复操作`
    };

    return (
        <AuthComponent code="office:recruitment:course:resume:comment">
            <Row type="flex" align="middle">
                <ThumbComment {...likeProps} onClick={() => handleClick(likeProps.type)}></ThumbComment>
                <Divider type="vertical" />
                <ThumbComment {...dislikeProps} onClick={() => handleClick(dislikeProps.type)}></ThumbComment>
                {/* 弹框 */}
                <CommentModal
                    resumeId={resumeId}
                    operate={operate}
                    onOk={handleOkClick}
                    onCancel={handleCancelClick}
                    {...modalProps}
                    flag={flag}
                ></CommentModal>
            </Row>
        </AuthComponent>
    );
};
export default ThumbCommentGroup;
